(function() {
  var $usernameInput, dataKey, editModel, getTrHtml, loginInfo, saveUserData, setPy, showUserData;

  dataKey = 'login_taobao_com';

  loginInfo = {};

  saveUserData = function() {
    var obj;
    obj = {};
    obj[dataKey] = $('form').serializeObject();
    return chrome.storage.local.set(obj);
  };

  editModel = function() {
    $('table').addClass('editModel');
    return $('input').removeAttr('readonly');
  };

  setPy = function(save) {
    var cnt;
    if (save == null) {
      save = false;
    }
    cnt = 0;
    return $('[name="username[]"]').each(function() {
      var that;
      that = this;
      if (this.value) {
        cnt++;
        return $.getJSON('http://huoqu.sinaapp.com/pinyin/', {
          m: 'JSON',
          a: this.value
        }, function(data) {
          var pyEle, thisPy;
          pyEle = $(that).next();
          if (data != null ? data.all : void 0) {
            thisPy = data.all.toLowerCase();
            if (pyEle.val() !== thisPy) {
              pyEle.val(thisPy);
            }
          }
          if (save && !--cnt) {
            return saveUserData();
          }
        });
      }
    });
  };

  getTrHtml = function(name, password, py, show) {
    var className, usernameTitle;
    if (name == null) {
      name = '';
    }
    if (password == null) {
      password = '';
    }
    if (py == null) {
      py = "";
    }
    if (show == null) {
      show = true;
    }
    className = '';
    if (!show) {
      className = 'hide';
    }
    usernameTitle = '';
    if (py) {
      usernameTitle = "拼音：" + py;
    }
    return "<tr class=\"" + className + "\">\n	<td>\n		<input name=\"username[]\" title=\"" + usernameTitle + "\" type=\"text\" value=\"" + (htmlEncode(name)) + "\" placeholder=\"输入旺旺用户名\" readonly=\"readonly\" />\n		<input name=\"userPY[]\" type=\"hidden\" value=\"" + (htmlEncode(py)) + "\" />\n	</td>\n	<td class=\"passCol\">\n		<input name=\"password[]\" type=\"password\" value=\"" + (htmlEncode(password)) + "\" placeholder=\"输入旺旺密码\" />\n	</td>\n	<td>\n		<button class=\"btn loginAction btn-primary\" type=\"button\">登录</button>\n	</td>\n</tr>";
  };

  showUserData = function(search, callback) {
    var sep;
    if (search == null) {
      search = '';
    }
    if (callback == null) {
      callback = '';
    }
    search = search.replace(/[.{}| $^*+?\[\]]/g, '');
    if (search) {
      sep = '.*';
      search = search.split('');
      search = search.join(sep);
      search = search.toLowerCase();
      search = new RegExp(search);
    }
    return chrome.storage.local.get(dataKey, function(item) {
      var i, obj, tbody, v, _i, _len, _ref;
      obj = {
        username: [''],
        password: ['']
      };
      if (item && item[dataKey]) {
        obj = item[dataKey];
      }
      tbody = '';
      if (obj.username) {
        _ref = obj.username;
        for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
          v = _ref[i];
          if (!v) {
            continue;
          }
          tbody += getTrHtml(v, obj.password[i], obj.userPY[i], !search || search.test(v.toLowerCase()) || search.test(obj.userPY[i]));
        }
      }
      if (!tbody) {
        tbody += getTrHtml();
      }
      $('tbody').html(tbody);
      if ($.isFunction(callback)) {
        return callback();
      }
    });
  };

  showUserData();

  $('#save').click(function() {
    saveUserData();
    return setPy(true);
  });

  $('#addLine').click(function() {
    var newLine;
    newLine = $(getTrHtml());
    $('tbody').append(newLine);
    editModel();
    return newLine.find('[name="username[]"]').focus();
  });

  $('#edit').click(editModel);

  $('.loginAction').live('click', function() {
    var $tr, password, passwordEle, username, usernameEle;
    saveUserData();
    setPy(true);
    $tr = $(this).closest('tr');
    usernameEle = $('[name="username[]"]', $tr);
    username = usernameEle.val();
    passwordEle = $('[name="password[]"]', $tr);
    password = passwordEle.val();
    if (!username) {
      alert('请输入用户名');
      usernameEle.focus();
      return false;
    }
    if (!password) {
      alert('请认输密码');
      passwordEle.focus();
      return false;
    }
    loginInfo = {
      username: username,
      password: password
    };
    delCook();
    noProxy();
    chrome.extension.getBackgroundPage().msg('loginInfo', loginInfo);
    return setTimeout(function() {
      return open('http://trade.taobao.com/trade/itemlist/list_bought_items.htm');
    }, 900);
  });

  $usernameInput = $('[name="username[]"]').live('keyup', function() {
    var password, username, _ref;
    _ref = this.value.split("\t"), username = _ref[0], password = _ref[1];
    if (password) {
      this.value = username;
      return $(this).closest('tr').find('[name="password[]"]').val(password);
    }
  });

  $usernameInput.live('blur', function() {
    return this.value = this.value.trim();
  });

  $('#search').focus().keyup(function(e) {
    var btn;
    showUserData(this.value, function() {
      var btn, help;
      btn = $('tbody tr td button:visible');
      help = $('.help-block');
      if (1 === btn.size()) {
        return help.text("回车直接使用“" + ($('[name*=username]', btn.closest('tr')).val()) + "”登录").removeClass('hide');
      } else {
        return help.addClass('hide');
      }
    });
    btn = $('tbody tr td button:visible');
    if (13 === e.keyCode) {
      if (1 === btn.size()) {
        return btn.click();
      }
    }
  });

}).call(this);
